package com.pengtu.service.history;

import java.util.List;

import org.jbpm.api.ProcessInstance;
import org.jbpm.api.model.ActivityCoordinates;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.pengtu.dao.Page;
import com.pengtu.dao.history.HistoryProjectDao;
import com.pengtu.entity.history.HistoryProject;
import com.pengtu.entity.project.ProjectInfo;
import com.pengtu.model.ActivityModel;
import com.pengtu.service.JbpmTemplateManager;

@Component
@Transactional
public class HistoryProjectManager {
	private HistoryProjectDao historyProjectDao;

	private JbpmTemplateManager jbpmTemplateManager;

	@Autowired
	public void setHistoryProjectDao(HistoryProjectDao historyProjectDao) {
		this.historyProjectDao = historyProjectDao;
	}

	@Autowired
	public void setJbpmTemplateManager(JbpmTemplateManager jbpmTemplateManager) {
		this.jbpmTemplateManager = jbpmTemplateManager;
	}

	/**
	 * 保存
	 * 
	 * @param entity
	 */
	public void save(HistoryProject entity) {
		historyProjectDao.save(entity);
	}

	/**
	 * 根据任务ID查询
	 * 
	 * @param taskId
	 * @return
	 */
	public HistoryProject get(String taskId) {
		return historyProjectDao.findUniqueBy("taskId", taskId);
	}

	public HistoryProject getHistoryProject(String id) {
		return historyProjectDao.get(id);
	}

	/**
	 * 删除历史记录
	 * delete:
	 * 适用:
	 * @param historyProject 
	 * @exception 
	 * @since  1.0.0
	 */
	public void delete(HistoryProject historyProject) {
		historyProjectDao.delete(historyProject);
	}

	/**
	 * 根据执行人查询
	 * 
	 * @param taskId
	 * @return
	 */
	public List<HistoryProject> getAll(String userName) {
		return historyProjectDao.findBy("userName", userName);
	}

	/**
	 * 查询taskId
	 * 
	 * @param projectInfo
	 * @param status
	 * @return
	 */
	public String getTaskId(ProjectInfo projectInfo, String status) {
		HistoryProject historyProject = historyProjectDao.findByHistoryProject(
				projectInfo, status);
		String taskId = null;
		if (historyProject != null) {
			taskId = historyProject.getTaskId();
		}
		return taskId;
	}

	public List<HistoryProject> getHistoryProjects(String id) {
		return historyProjectDao.findBy("key", id,"startDate",Page.ASC);
	}

	/**
	 * 通过业务ID获得坐标 getActivityNames: 适用:
	 * 
	 * @param id
	 * @return
	 * @exception
	 * @since 1.0.0
	 */
	public ActivityModel getActivityNames(String id) {
		ActivityModel activityModel = new ActivityModel();
		ProcessInstance processInstance = jbpmTemplateManager
				.getProcessInstance(id);
		ActivityCoordinates ac = jbpmTemplateManager
				.getAllActivityNames(processInstance);
		List<String> map = jbpmTemplateManager.getAssignName(processInstance);
		activityModel.setActivityCoordinates(ac);
		activityModel.setAssigns(map);
		return activityModel;
	}
}
